package com.ruoyi.project.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.project.system.domain.SmsResponse;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISendPhoneCodeService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @Classname SendPhoneCodeServiceImpl
 * @Description TODO
 * @Author h21448-hxtq
 * @Date 2020-04-09 15 : 48
 * @Version 1.0
 */
@Service
public class SendPhoneCodeServiceImpl implements ISendPhoneCodeService {

    @Value("${baseframe.ali.accessKeyId}")
    private String accessKeyId;
    @Value("${baseframe.ali.accessSecret}")
    private String accessSecret;
    @Value("${baseframe.ali.signName}")
    private String signName;
    @Value("${baseframe.ali.templateCode}")
    private String templateCode;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private SysUserMapper userMapper;

    public SmsResponse sendPhoneCode(String phone) {
        SmsResponse smsResponse = new SmsResponse();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,  accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        //接收短信的手机号码、模板、签名
        request.putQueryParameter("PhoneNumbers",phone.trim());
        request.putQueryParameter("SignName", signName);
        //短信模板ID
        request.putQueryParameter("TemplateCode", templateCode);
        // 生成随机的短信验证码
        String random = RandomStringUtils.random(6, false, true);
        request.putQueryParameter("TemplateParam","{\"code\":\"" + random + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String code = (String)jsonObject.get("Code");
            if (StrUtil.isNotEmpty(code) && "OK".equals(code)) {
                smsResponse.setSmsCode(random);
                smsResponse.setSmsPhone(phone);
                smsResponse.setSmsTime(System.nanoTime()+"");
                return smsResponse;
            } else {
                throw new CustomException("给"+phone+"发送短信失败");
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new CustomException("给"+phone+"发送短信失败,"+e.getMessage());
        }

        return null;
    }

    public SmsResponse sendMailCode(String mailAddress) {
        SysUser sysUser = userMapper.checkEmailUnique(mailAddress);
        SmsResponse smsResponse = new SmsResponse();
        if (ObjectUtil.isNull(sysUser)) {
            throw new CustomException("该邮箱账号不存在");
        }
        try {
            String mailCode = RandomStringUtils.random(6, false, true);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(mailAddress);
            message.setText("您的验证码为：" + mailCode + "，请不要告诉任何人哟，15分钟内有效。");
            message.setSubject("邮箱验证");
            mailSender.send(message);

            smsResponse.setSmsCode(mailCode);
            smsResponse.setMailAddress(mailAddress);
            smsResponse.setSmsTime(System.nanoTime()+"");

        } catch (Exception e) {
            throw new CustomException("邮箱验证码发送失败，"+e.getMessage());
        }

        return smsResponse;

    }
}
